<template>
  <!-- 设备管理 -->
  <div id="saleSettleEditDiv">
    <div style="width: 100%;height: 100%;">
      <el-container class="container">
        <el-steps :active="active" finish-status="success" simple style="background-color: rgba(135, 206, 235, 0.45);height: 30px;width: 34%;margin-top: 10px;">
          <el-step title="选择结算单位"></el-step>
          <el-step title="收费项目结算"></el-step>
        </el-steps>
        <el-card style="margin-top: 10px;width: 100%;height: calc(100% - 66px);">
          <div v-if="active === 1" style="height: 100%;">
            <vxe-toolbar perfect>
              <template #buttons>
                <el-form :model="searchForm" class="form-input-m" style="height: 30px" label-width="80px" :inline="true">
                  <el-form-item label="关键字查询" clearable>
                    <vxe-input type="text" v-model="searchForm.searchValue" clearable @blur="findFinanceSettleList"></vxe-input>
                  </el-form-item>
                  <el-form-item label="结算日期" clearable>
                    <vxe-input v-model="searchForm.settleDateBegin" type="date" placeholder="起始日期" clearable transfer />
                    <div>-</div>
                    <vxe-input v-model="searchForm.settleDateEnd" type="date" placeholder="截至日期" clearable transfer />
                  </el-form-item>
                  <el-form-item>
                    <vxe-button type="text" class="button-blue" content="查询" @click="findFinanceSettleList"></vxe-button>
                  </el-form-item>
                </el-form>
              </template>
            </vxe-toolbar>
            <div class="tableBody" style="height: calc(100% - 36px - 34px)">
              <Splitpanes>
                <Pane size="15">
                  <div class="tableBox">
                    <vxe-table ref="companyTableRef" :data="settleCompanyList" :loading="mLoading" @current-change="settleCompanyRowClick" @checkbox-change="settleCompanyChangeRow" @checkbox-all="settleCompanyAllChangeRow" border class="mytable-scrollbar" show-header-overflow show-overflow align="center" :row-config="{ isCurrent: true, isHover: true }" height="auto">
                      <vxe-column type="checkbox" width="30" fixed="left" align="center"></vxe-column>
                      <vxe-column field="companyName" title="送检单位"> </vxe-column>
                    </vxe-table>
                  </div>
                </Pane>
                <Pane size="85">
                  <div class="tableBox">
                    <vxe-table ref="settleTableRef" :data="sltSettleCompany.financeSettleList" @checkbox-change="financeSettleChangeRow" @checkbox-all="financeSettleAllChangeRow" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                      <vxe-column type="checkbox" width="30" fixed="left" align="center"></vxe-column>
                      <vxe-column field="settleNo" title="单据号">
                        <template #default="{ row }">
                          <el-link type="primary" :underline="false" @click="showPeople(row)">
                            <span>{{row.settleNo}}</span>
                          </el-link>
                        </template>
                      </vxe-column>
                      <vxe-column field="costs" title="总计金额"></vxe-column>
                      <vxe-column field="realCosts" title="实际金额"></vxe-column>
                      <vxe-column field="brokerageCosts" title="销售提成"></vxe-column>
                      <vxe-column field="settleDate" title="结算时间"></vxe-column>
                    </vxe-table>
                  </div>
                </Pane>
              </Splitpanes>
            </div>
            <div style="float: right;margin-right: 40px;">
              <vxe-button type="text" class="button-blue" @click="next">下一步</vxe-button>
            </div>
          </div>
          <div v-if="active === 2" style="height: 100%">
            <div class="tableBody" style="height: calc(100% - 34px)">
              <vxe-table ref="saleSettleTableRef" :data="saleSettleForm.saleSettleDetail" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :show-footer="true" :footer-method="footerMethod" resizable show-overflow keep-source>
                <vxe-column field="companyName" title="送检单位"> </vxe-column>
                <vxe-column field="settleNum" title="单据数量"></vxe-column>
                <vxe-column field="costs" title="总计金额"></vxe-column>
                <vxe-column field="realCosts" title="实际金额"></vxe-column>
                <vxe-column field="brokerageCosts" title="销售提成"></vxe-column>
              </vxe-table>
            </div>
            <div style="display: flex;align-items: center;justify-content: space-between;">
              <div>
                <el-descriptions :column="10" :labelStyle="{ width: '110px', background: '#fff', color: '#000', textAlign: 'center' }" :contentStyle="{ width: '130px' }" border>
                </el-descriptions>
              </div>
              <div style="margin-right: 40px;">
                <vxe-button :disabled="!checkChkShow" :loading="sloading" type="text" class="button-blue" icon="vxe-icon-save" content="结算" @click="saveSaleSettle"></vxe-button>
                <vxe-button type="text" class="button-blue" @click="upper">上一步</vxe-button>
              </div>
            </div>
          </div>
        </el-card>
      <FinanceShowPeople ref="financeShowPeopleRef"></FinanceShowPeople>
      </el-container>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import FinanceShowPeople from '@/components/FinanceShowPeople.vue';
let financeShowPeopleRef=ref(null);
import Breadcrumb from '@/components/Breadcrumb.vue';
import moment from 'moment';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { AppStore } from '@/stores/store'; //'../../../stores/store';
import { VXETable, VxeFormPropTypes, VxeFormInstance } from 'vxe-table';
import { IsEmpty, formatDateTime, autoIncrementNumber, sortByField } from '@/utils/common';
let { proxy }: any = getCurrentInstance();
let store = AppStore();
//暴露属性和方法
defineExpose({
  initPage
});

let active = ref(1);
let sloading = ref(false);
let checkChkShow = ref(true);
let searchForm = reactive({
  searchValue: '',
  settleDateBegin: '',
  settleDateEnd: ''
});

let saleSettleForm = reactive({
  id: null,
  salesStatus: '',
  salesCode: '',
  salesmanCode: '',
  salesmanName: '',
  saleSettleDetail: []
});
let salesmanObj: any = reactive({});
function initPage(sltSalesman: any) {
  console.log(sltSalesman);
  if (!IsEmpty(sltSalesman)) {
    salesmanObj = sltSalesman;
    findFinanceSettleList();
  } else {
    salesmanObj = {};
  }
}
let mLoading = ref(false); //刷新加载状态
let settleCompanyList: any = reactive([]);
let sltSettleCompany: any = ref({});
let sltFinanceSettleList: any = reactive([]);
const footerData = ref([['总计金额', , , ,]]);

function findFinanceSettleList() {
  mLoading.value = true;
  settleCompanyList.length = 0; //放入数据前清空数据
  const url = '/lab/financeSettle/findCompanyAndFinanceSettleList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        searchValue: searchForm.searchValue,
        settleStatus: '10',
        salesmanCode: salesmanObj.code,
        settleDateBegin: searchForm.settleDateBegin,
        settleDateEnd: searchForm.settleDateEnd
      }
    })
    .then((res: any) => {
      settleCompanyList.push(...res.data);
      if (settleCompanyList.length == 0) {
        sltSettleCompany.value = {};
      } else {
        const kn = settleCompanyList.find((k: any) => k.id == sltSettleCompany.value.id);
        if (IsEmpty(kn)) {
          settleCompanyRowClick({ row: settleCompanyList[0] }); //默认选中第一条数据
        } else {
          settleCompanyRowClick({ row: kn }); //默认选中第一条数据
        }
        //默认全选
        proxy.$nextTick(() => {
          defaultAllCheckboxAllCompany();
        });
      }

      mLoading.value = false;
    })
    .catch((err: any) => {
      mLoading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function settleCompanyRowClick({ row }: any) {
  if (IsEmpty(row)) {
    sltSettleCompany.value = {};
  } else {
    (proxy.$refs.companyTableRef as any).setCurrentRow(row);
    sltSettleCompany.value = row;
    proxy.$nextTick(() => {
      setSettleTableCheckBox();
    });
  }
}

function settleCompanyChangeRow(checkedRows) {
  if (checkedRows.checked) {
    for (const setobj of checkedRows.row.financeSettleList) {
      const kn = sltFinanceSettleList.find((k: any) => !IsEmpty(k) && k.settleNo == setobj.settleNo);
      if (IsEmpty(kn)) {
        sltFinanceSettleList.push(setobj);
      }
    }
  } else {
    for (const setobj of checkedRows.row.financeSettleList) {
      const cnt = sltFinanceSettleList.findIndex((k: any) => k.settleNo == setobj.settleNo);
      if (cnt > -1) {
        sltFinanceSettleList.splice(cnt, 1);
      }
    }
  }
  setSettleTableCheckBox();
}

function settleCompanyAllChangeRow(checkedRows) {
  if (checkedRows.checked) {
    for (const re of checkedRows.records) {
      for (const setobj of re.financeSettleList) {
        const kn = sltFinanceSettleList.find((k: any) => !IsEmpty(k) && k.settleNo == setobj.settleNo);
        if (IsEmpty(kn)) {
          sltFinanceSettleList.push(setobj);
        }
      }
    }
  } else {
    sltFinanceSettleList.length = 0;
  }

  setSettleTableCheckBox();
}
function financeSettleChangeRow(checkedRows) {
  if (checkedRows.checked) {
    const kn = sltFinanceSettleList.find((k: any) => !IsEmpty(k) && k.settleNo == checkedRows.row.settleNo);
    if (IsEmpty(kn)) {
      sltFinanceSettleList.push(checkedRows.row);
    }
  } else {
    const cnt = sltFinanceSettleList.findIndex((k: any) => k.settleNo == checkedRows.row.settleNo);
    if (cnt > -1) {
      sltFinanceSettleList.splice(cnt, 1);
    }
  }
}

function financeSettleAllChangeRow(checkedRows) {
  if (checkedRows.checked) {
    for (const re of checkedRows.records) {
      const kn = sltFinanceSettleList.find((k: any) => !IsEmpty(k) && k.settleNo == re.settleNo);
      if (IsEmpty(kn)) {
        sltFinanceSettleList.push(re);
      }
    }
  } else {
    for (const re of sltSettleCompany.value.financeSettleList) {
      const cnt = sltFinanceSettleList.findIndex((k: any) => k.settleNo == re.settleNo);
      if (cnt > -1) {
        sltFinanceSettleList.splice(cnt, 1);
      }
    }
  }
}

function setSettleTableCheckBox() {
  const $table = proxy.$refs.settleTableRef;
  if ($table) {
    $table.clearCheckboxRow();
  }
  if (sltFinanceSettleList.length > 0) {
    const sltFeeItemList = [];
    for (const redo of sltFinanceSettleList) {
      const jj = sltSettleCompany.value.financeSettleList.find((item: any) => item.settleNo == redo.settleNo);
      if (!IsEmpty(jj)) {
        sltFeeItemList.push(jj);
      }
    }
    if ($table) {
      $table.setCheckboxRow(sltFeeItemList, true);
    }
  }
}

function defaultAllCheckboxAllCompany() {
  const $table = proxy.$refs.companyTableRef;
  if ($table) {
    $table.setCheckboxRow(settleCompanyList, true);
  }
  sltFinanceSettleList.length = 0;
  //全选财务结算单
  for (const re of settleCompanyList) {
    for (const setobj of re.financeSettleList) {
      const kn = sltFinanceSettleList.find((k: any) => !IsEmpty(k) && k.settleNo == setobj.settleNo);
      if (IsEmpty(kn)) {
        sltFinanceSettleList.push(setobj);
      }
    }
  }
  setSettleTableCheckBox();
}

function saveSaleSettle() {
  if (saleSettleForm.saleSettleDetail.length == 0) {
    VxeMessage('结算单位', VxeNotifyType.error);
    return;
  }
  sloading.value = true;
  const url = '/lab/financeSalesSettle/saveFinanceSalesSettle';
  const supplier = {
    salesmanCode: saleSettleForm.salesmanCode,
    salesmanName: saleSettleForm.salesmanName,
    settleStatus: saleSettleForm.salesStatus,
    salesSettleDetalls: saleSettleForm.saleSettleDetail
  };
  proxy.$http
    .post(url, supplier)
    .then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage('操作成功', VxeNotifyType.success);
        checkChkShow.value = false;
      } else {
        VxeMessage('操作失败', VxeNotifyType.error);
      }
      sloading.value = false;
    })
    .catch((err: any) => {
      sloading.value = false;
      console.log(err);
      VxeMessage('操作失败', VxeNotifyType.error);
    });
}
function next() {
  saleSettleForm.saleSettleDetail.length = 0;
  //拼接销售结算单
  saleSettleForm.salesStatus = '5';
  saleSettleForm.salesmanCode = salesmanObj.code;
  saleSettleForm.salesmanName = salesmanObj.name;

  const cc = sltFinanceSettleList.map((a: any) => a.companyCode);
  let set = new Set(cc);
  let arr = Array.from(set);
  for (const co of arr) {
    let saleDetail: any = {};
    let fslist: any = sltFinanceSettleList.filter((data) => data.companyCode === co);
    saleDetail.settleNum = fslist.length;
    saleDetail.companyCode = fslist[0].companyCode;
    saleDetail.companyName = fslist[0].companyName;
    saleDetail.settleNo = fslist.map((item: any) => item.settleNo).join(',');
    let costs = 0;
    let realCosts = 0;
    let brokerageCosts = 0;
    for (const sFs of fslist) {
      costs += sFs.costs;
      realCosts += sFs.realCosts;
      brokerageCosts += sFs.brokerageCosts;
    }
    saleDetail.costs = costs;
    saleDetail.realCosts = realCosts;
    saleDetail.brokerageCosts = brokerageCosts;
    saleSettleForm.saleSettleDetail.push(saleDetail);
  }

  active.value = 2;
}

function footerMethod() {
  let settleNum = 0;
  let costs = 0;
  let realCosts = 0;
  let brokerageCosts = 0;
  saleSettleForm.saleSettleDetail.forEach((element) => {
    settleNum += element.settleNum;
    costs += element.costs;
    realCosts += element.realCosts;
    brokerageCosts += element.brokerageCosts;
  });
  footerData.value = [['总计金额', settleNum + '', costs + '', realCosts + '', brokerageCosts + '']];
  return footerData.value;
}
function upper() {
  active.value = 1;
  //默认全选
  proxy.$nextTick(() => {
    defaultAllCheckboxAllCompany();
  });
}

function showPeople(row :any) {
  financeShowPeopleRef.value.initPage(row);
}
</script>
<style lang="scss">
#saleSettleEditDiv {
  height: 100%;
  .vxe-cell--item {
    font-weight: bold;
  }

  .container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    /*justify-content: center;*/
    align-items: center;
    background-color: $base-white;
    .el-card {
      .el-card__body {
        padding: 0;
        height: 100%;
      }
    }
  }
  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }
  .tableBox {
    height: 100%;
    background-color: $base-white;
  }

  .footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 5px 0;
    box-shadow: 8px 8px 15px #909399;
    background-color: $bg-gray;
    z-index: 9999;
    .el-form {
      transform: translateX(5%);
    }
    .el-form-item {
      margin-bottom: 0;
      margin-right: 12px;
    }
  }
}
</style>